<template>
  <div class="dashboard-container">
    <!-- 顶部统计卡片 -->
    <div class="stats-cards">
      <div class="stat-card blue">
        <div class="icon-container">
          <el-icon><User /></el-icon>
        </div>
                <div class="stat-content">
          <div class="stat-number">{{ overviewData.residentCount }}</div>
          <div class="stat-label">居民数量</div>
        </div>
      </div>

      <div class="stat-card green">
        <div class="icon-container">
          <el-icon><Document /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ overviewData.contractCount }}</div>
          <div class="stat-label">签约数量</div>
        </div>
      </div>

      <div class="stat-card orange">
        <div class="icon-container">
          <el-icon><Star /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ overviewData.serviceCount }}</div>
          <div class="stat-label">服务次数</div>
        </div>
      </div>

      <div class="stat-card red">
        <div class="icon-container">
          <el-icon><Warning /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ overviewData.exceptionCount }}</div>
          <div class="stat-label">异常情况</div>
        </div>
      </div>
    </div>

    <!-- 中间内容区域 -->
    <div class="content-row">
      <!-- 左侧数据概况图表 -->
      <div class="chart-container">
        <div class="chart-header">
          <h3>数据概况</h3>
          <div class="legend">
            <span class="legend-item blue-dot">居民数量</span>
            <span class="legend-item green-dot">签约量</span>
            <span class="legend-item red-dot">服务量</span>
          </div>
        </div>
        <div ref="lineChartRef" class="chart" style="height: 300px;"></div>
      </div>

      <!-- 右侧待办提醒 -->
      <div class="todo-container">
        <div class="todo-header">
          <h3>待办提醒</h3>
        </div>
        <div class="todo-list">
          <div class="todo-item" v-for="(todo, index) in todoList" :key="index">
            <div class="todo-number">{{ todo.number }}</div>
            <div class="todo-text">{{ todo.text }}</div>
            <div class="todo-dot red"></div>
          </div>
        </div>
      </div>
    </div>

    <!-- 下方内容区域 -->
    <div class="bottom-content">
      <!-- 左侧居民标签图表 -->
      <div class="tag-chart-container">
        <div class="chart-header">
          <h3>病况统计</h3>
        </div>
        <div ref="barChartRef" class="chart" style="height: 250px;"></div>
      </div>

      <!-- 中间居民指标界面 -->
      <div class="doctor-cards-container">
        <div class="doctor-header">
          <h3>居民健康状况</h3>
          <span class="view-all" @click="openResident()">全部 ></span>
        </div>
        <div class="doctor-cards">
          <div class="doctor-card" v-for="(doctor, index) in doctors" :key="index">
            <div class="doctor-avatar">
              <img :src="doctor.avatar" :alt="doctor.name" />
            </div>
            <div class="doctor-info">
              <div class="doctor-name">{{ doctor.name }}</div>
              <div class="doctor-title">{{ doctor.title }}</div>
              <div class="doctor-status">
                <span class="status-dot"></span>
                {{ doctor.status }}
              </div>
            </div>
            <div class="doctor-actions">
              <el-button type="primary" size="small" @click="viewResidentDetail(doctor)">查看详情</el-button>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧本周签约情况表格 -->
      <div class="weekly-table-container">
        <div class="table-header">
          <h3>本周签约情况</h3>
        </div>
        <el-table :data="weeklyData" style="width: 100%" size="small">
          <el-table-column prop="team" label="团队" width="100"></el-table-column>
          <el-table-column prop="day1" :label="dateLabels[0] || '第1天'" width="90"></el-table-column>
          <el-table-column prop="day2" :label="dateLabels[1] || '第2天'" width="90"></el-table-column>
          <el-table-column prop="day3" :label="dateLabels[2] || '第3天'" width="90"></el-table-column>
          <el-table-column prop="day4" :label="dateLabels[3] || '第4天'" width="90"></el-table-column>
          <el-table-column prop="day5" :label="dateLabels[4] || '第5天'" width="90"></el-table-column>
          <el-table-column prop="day6" :label="dateLabels[5] || '第6天'" width="90"></el-table-column>
          <el-table-column prop="day7" :label="dateLabels[6] || '第7天'" width="90"></el-table-column>
        </el-table>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import * as echarts from 'echarts'
import { User, Document, Star, Warning } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import axios from 'axios'

const router = useRouter()

// 图表引用
const lineChartRef = ref()
const barChartRef = ref()

// 数据状态
const overviewData = ref({
  residentCount: 0,
  contractCount: 0,
  serviceCount: 0,
  exceptionCount: 0
})

const todoList = ref([])
const doctors = ref([])
const weeklyData = ref([])
const dateLabels = ref([])

// 初始化折线图
const initLineChart = (trendData) => {
  const chart = echarts.init(lineChartRef.value)

  const option = {
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: trendData?.dates || ['1/4', '1/5', '1/6', '1/7', '1/8', '1/9', '1/10'],
      axisLine: { show: false },
      axisTick: { show: false }
    },
    yAxis: {
      type: 'value',
      axisLine: { show: false },
      axisTick: { show: false },
      splitLine: {
        lineStyle: {
          color: '#f0f0f0'
        }
      }
    },
    series: [
      {
        name: '居民数量',
        type: 'line',
        data: trendData?.residentData || [280, 300, 260, 240, 180, 220, 260],
        itemStyle: { color: '#409eff' },
        lineStyle: { color: '#409eff', width: 2 },
        symbol: 'circle',
        symbolSize: 6
      },
      {
        name: '签约量',
        type: 'line',
        data: trendData?.contractData || [100, 110, 200, 180, 140, 120, 110],
        itemStyle: { color: '#67c23a' },
        lineStyle: { color: '#67c23a', width: 2 },
        symbol: 'circle',
        symbolSize: 6
      },
      {
        name: '服务量',
        type: 'line',
        data: trendData?.serviceData || [120, 140, 220, 200, 300, 150, 180],
        itemStyle: { color: '#f56c6c' },
        lineStyle: { color: '#f56c6c', width: 2 },
        symbol: 'circle',
        symbolSize: 6
      }
    ]
  }

  chart.setOption(option)

  // 响应式
  window.addEventListener('resize', () => {
    chart.resize()
  })
}

// 初始化柱状图
const initBarChart = (tagData) => {
  const chart = echarts.init(barChartRef.value)

  const option = {
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'value',
      axisLine: { show: false },
      axisTick: { show: false },
      splitLine: { show: false }
    },
    yAxis: {
      type: 'category',
      data: tagData?.tagNames || ['老年症', '多动症', '高血压', '高血脂', '慢病护理', '高血压'],
      axisLine: { show: false },
      axisTick: { show: false }
    },
    series: [
      {
        type: 'bar',
        data: tagData?.tagCounts || [88, 110, 30, 40, 120, 200],
        itemStyle: {
          color: '#409eff',
          borderRadius: [0, 4, 4, 0]
        },
        barWidth: 20
      }
    ]
  }

  chart.setOption(option)

  // 响应式
  window.addEventListener('resize', () => {
    chart.resize()
  })
}

// API调用方法
const fetchOverviewData = async () => {
  try {
    const response = await axios.get('/dashboard/overview')
    overviewData.value = response.data
  } catch (error) {
    console.error('获取概况数据失败:', error)
  }
}

const openResident = () =>{
  router.push("/main/dashboard")
}

const fetchTrendData = async () => {
  try {
    const response = await axios.get('/dashboard/trend')
    const trendData = response.data
    nextTick(() => {
      initLineChart(trendData)
    })
  } catch (error) {
    console.error('获取趋势数据失败:', error)
    nextTick(() => {
      initLineChart()
    })
  }
}

const fetchTodoData = async () => {
  try {
    const response = await axios.get('/dashboard/todo')
    todoList.value = response.data.todoList
  } catch (error) {
    console.error('获取待办数据失败:', error)
  }
}

const fetchTagStats = async () => {
  try {
    const response = await axios.get('/dashboard/tags')
    const tagData = response.data
    nextTick(() => {
      initBarChart(tagData)
    })
  } catch (error) {
    console.error('获取标签统计失败:', error)
    nextTick(() => {
      initBarChart()
    })
  }
}

const fetchDoctorCards = async () => {
  try {
    const response = await axios.get('/dashboard/doctors')
    doctors.value = response.data.doctors
  } catch (error) {
    console.error('获取医生数据失败:', error)
  }
}

const fetchWeeklyData = async () => {
  try {
    const response = await axios.get('/dashboard/weekly')
    const data = response.data
    weeklyData.value = data.weeklyData
    dateLabels.value = data.dateLabels
  } catch (error) {
    console.error('获取周数据失败:', error)
  }
}

// 查看居民详情
const viewResidentDetail = (resident) => {
  router.push({
    name: 'ResidentDetail',
    query: { id: resident.id }
  })
}

// 初始化所有数据
const initAllData = async () => {
  await Promise.all([
    fetchOverviewData(),
    fetchTrendData(),
    fetchTodoData(),
    fetchTagStats(),
    fetchDoctorCards(),
    fetchWeeklyData()
  ])
}

onMounted(() => {
  initAllData()
})
</script>

<style scoped>
.dashboard-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

/* 顶部统计卡片 */
.stats-cards {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
  margin-bottom: 20px;
}

.stat-card {
  background: white;
  border-radius: 8px;
  padding: 20px;
  display: flex;
  align-items: center;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.icon-container {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
  font-size: 24px;
  color: white;
}

.stat-card.blue .icon-container {
  background: #409eff;
}

.dashboard-container {
  width: 1400px;
  margin: 0 auto;
}

.stat-card.green .icon-container {
  background: #67c23a;
}

.stat-card.orange .icon-container {
  background: #e6a23c;
}

.stat-card.red .icon-container {
  background: #f56c6c;
}

.stat-content {
  flex: 1;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  line-height: 1;
}

.stat-card.blue .stat-number {
  color: #409eff;
}

.stat-card.green .stat-number {
  color: #67c23a;
}

.stat-card.orange .stat-number {
  color: #e6a23c;
}

.stat-card.red .stat-number {
  color: #f56c6c;
}

.stat-label {
  font-size: 14px;
  color: #909399;
  margin-top: 5px;
}

/* 中间内容区域 */
.content-row {
  display: grid;
  grid-template-columns: 1fr 300px;
  gap: 20px;
  margin-bottom: 20px;
}

.chart-container, .todo-container {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.chart-header, .todo-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.chart-header h3, .todo-header h3 {
  margin: 0;
  font-size: 16px;
  color: #303133;
}

.legend {
  display: flex;
  gap: 20px;
}

.legend-item {
  display: flex;
  align-items: center;
  font-size: 12px;
  color: #606266;
}

.legend-item::before {
  content: '';
  width: 8px;
  height: 8px;
  border-radius: 50%;
  margin-right: 6px;
}

.blue-dot::before { background: #409eff; }
.green-dot::before { background: #67c23a; }
.red-dot::before { background: #f56c6c; }

/* 待办事项 */
.todo-list {
  space-y: 15px;
}

.todo-item {
  display: flex;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
}

.todo-item:last-child {
  border-bottom: none;
}

.todo-number {
  font-size: 20px;
  font-weight: bold;
  color: #303133;
  width: 40px;
}

.todo-text {
  flex: 1;
  color: #606266;
  margin-left: 10px;
}

.todo-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
}

.todo-dot.red {
  background: #f56c6c;
}

/* 底部内容区域 */
.bottom-content {
  display: grid;
  grid-template-columns: 300px 1fr 400px;
  gap: 20px;
}

.tag-chart-container, .doctor-cards-container, .weekly-table-container {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

/* 医生卡片 */
.doctor-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.doctor-header h3 {
  margin: 0;
  font-size: 16px;
  color: #303133;
}

.view-all {
  color: #409eff;
  font-size: 12px;
  cursor: pointer;
}

.doctor-cards {
  display: flex;
  gap: 15px;
}

.doctor-card {
  flex: 1;
  text-align: center;
  padding: 15px;
  border: 1px solid #f0f0f0;
  border-radius: 8px;
}

.doctor-avatar {
  margin-bottom: 10px;
}

.doctor-avatar img {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  object-fit: cover;
}

.doctor-name {
  font-weight: bold;
  color: #303133;
  margin-bottom: 5px;
}

.doctor-title {
  font-size: 12px;
  color: #909399;
  margin-bottom: 8px;
}

.doctor-status {
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  color: #f56c6c;
  margin-bottom: 15px;
}

.status-dot {
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background: #f56c6c;
  margin-right: 4px;
}

/* 表格 */
.table-header {
  margin-bottom: 15px;
}

.table-header h3 {
  margin: 0;
  font-size: 16px;
  color: #303133;
}

/* 响应式 */
@media (max-width: 1200px) {
  .stats-cards {
    grid-template-columns: repeat(2, 1fr);
  }

  .content-row {
    grid-template-columns: 1fr;
  }

  .bottom-content {
    grid-template-columns: 1fr;
  }

  .doctor-cards {
    flex-direction: column;
  }
}

:deep(.el-table) {
  font-size: 12px;
}

:deep(.el-table th) {
  background-color: #fafafa;
  color: #909399;
  font-weight: normal;
}

:deep(.el-table td) {
  padding: 8px 0;
}
</style>